package com.anjbo.controller.house;


import com.anjbo.bean.house.HouseHttpParamsDto;
import com.anjbo.bean.property.TZCPropertyDto;
import com.anjbo.common.*;
import com.anjbo.controller.common.StatisticsController;
import com.anjbo.service.house.HouseService;


import com.anjbo.service.property.PropertyAVGService;
import com.anjbo.utils.ConfigUtil;
import com.anjbo.utils.LoginCacheUtil;

import com.anjbo.utils.StringUtil;
import com.anjbo.utils.UidUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import org.apache.commons.collections.iterators.ObjectArrayIterator;
import org.apache.commons.collections.map.CompositeMap;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.enums.Enum;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import java.util.*;

/**
 * Created by zsy on 2017/3/6.
 */
@Controller
@RequestMapping(value = "/app/house/base")
public class HouseController {

    @Resource
    private HouseService houseService;


    /** 工具询价Url */
    private static final String autoPriceUrl = ConfigUtil.getStringValue(Enums.GLOBAL_CONFIG_KEY.TOOLS_URL.toString())+"/tools/enquiry/v/createEnquiry"; /** 工具询价Url */


    /**查询询价结果*/
    private static final String enquryPriceUrl = ConfigUtil.getStringValue(Enums.GLOBAL_CONFIG_KEY.TOOLS_URL.toString())+"/tools/enquiry/v/getEnquiryInfo";





    /**
     * 新增房产信息接口
     *
     * @return RespData
     */
    @ResponseBody
    @RequestMapping(value = "/v/insertBase")
    public RespDataObject<Map<String,String>> insertHouseBase(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        RespDataObject<Map<String,String>> resp = new RespDataObject<Map<String,String>>();
        HouseHttpParamsDto hpd = getHttpHouseParams(request, param);
       /* for (String key:param.keySet()) {
            System.out.print(key);
            System.out.println(param.get(key));
        }*/
        param.put("uid", hpd.getUid());
        param.put("areaChild", hpd.getCity());
        String orderNo=UidUtil.generateOrderId();//唯一orderNO
        param.put("orderNo",orderNo);//生成orderNo
        param.put("areaChild",hpd.getCity());
        param.put("createTime",new Date());
        if (StringUtils.isEmpty(hpd.getUid())) {
            resp.setCode(RespStatusEnum.FAIL.getCode());
            resp.setMsg("您的账号存在异常情况，请重新登录并修改密码！");
        } else {
            try {
                Map<String, Object> getAvgParam = new HashMap();
                int type=2;
                //封装参数调询价接口
                if(StringUtil.equals("深圳",hpd.getCity())||StringUtils.equals("广州",hpd.getCity())){
                    getAvgParam.put("type","2");
                }else{
                    getAvgParam.put("type","4");
                }

                getAvgParam.put("uid", hpd.getUid());
                getAvgParam.put("cityName",hpd.getCity());
               /* String propertyid=MapUtils.getString(param,"propertyid");
                propertyid= (String) param.get("propertyid");*/

                getAvgParam.put("propertyName",MapUtils.getString(param,"propertyName"));
                getAvgParam.put("propertyId",MapUtils.getString(param,"propertyid"));
                getAvgParam.put("buildingName",MapUtils.getString(param,"buildingName"));
                getAvgParam.put("buildingId", MapUtils.getString(param,"buildingid"));
                getAvgParam.put("roomName", MapUtils.getString(param,"roomName"));
                getAvgParam.put("roomId", MapUtils.getString(param,"roomid"));
                //getAvgParam.put("currentFloor",MapUtils.getIntValue(param,"roomid"));
                getAvgParam.put("area",MapUtils.getDouble(param,"acreage"));
                //getAvgParam.put("registerPrice", MapUtils.getDouble(param,"boughtPrice"));
                //getAvgParam.put("dealPrice", MapUtils.getIntValue(param,"roomid"));
                //getAvgParam.put("obligee", MapUtils.getIntValue(param,"roomid"));
                //getAvgParam.put("consumerloans", MapUtils.getIntValue(param,"roomid"));
                //getAvgParam.put("range", MapUtils.getIntValue(param,"roomid"));
                getAvgParam.put("isGetNetPriceTax",1);
                //getAvgParam.put("source", "0");
                //getAvgParam.put("device", MapUtils.getIntValue(param,"roomid"));
                //getAvgParam.put("version",MapUtils.getIntValue(param,"roomid"));
                Double unitPrice=0.0;
                //调用询价接口返回价格
                try {
                    //调用询价接口返回询价id
                    JSONObject resultJson = JSONObject.fromObject(HttpUtil.jsonPost(autoPriceUrl, getAvgParam));

                    Map<String,Object> enqueryPriceMap=new HashedMap();
                    int enquiryId = resultJson.getJSONObject("data").getInt("enquiryid");
                    //根据询价id查询询价结果
                    enqueryPriceMap.put("enquiryId",enquiryId);
                    JSONObject queryPriceList=JSONObject.fromObject(HttpUtil.jsonPost(enquryPriceUrl, enqueryPriceMap));
                    List list=queryPriceList.getJSONObject("data").getJSONArray("enquiryReportList");
                    for(int i=0;i<list.size();i++){
                        JSONObject jbo= (JSONObject) list.get(i);
                        unitPrice=jbo.getDouble("unitPrice");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                int i = houseService.insertHouse(param,unitPrice);
                Map<String,String> map=new HashedMap();
                map.put("orderNo",orderNo);
                resp.setData(map);
                resp.setCode(RespStatusEnum.SUCCESS.getCode());
                resp.setMsg(RespStatusEnum.SUCCESS.getMsg());
            } catch (Exception e) {
                RespHelper.setFailDataObject(resp,null,"哎呀，没有添加成功，请重新尝试～");
                e.printStackTrace();
            }

        }

        return resp;
    }

    /**
     * 封装获取http参数
     *\u6df1\u5733
     * @param request
     * @param param
     * @return
     */
    private HouseHttpParamsDto getHttpHouseParams(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        String sid = (String) request.getHeader("sid");
        String deviceId = (String) request.getHeader("deviceId");
        //String areaChild = (String) request.getHeader("city");//相应头获取
        HouseHttpParamsDto hpd = new HouseHttpParamsDto();
        //String areaChild = StringUtil.decode(request.getHeader("city"));
        String areaChild="";
        try {
            if(StringUtil.isNotEmpty(request.getHeader("city"))){
                areaChild = URLDecoder.decode(request.getHeader("city"), "utf-8");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(areaChild)) {
            areaChild = MapUtils.getString(param,"areaChild");
            if(StringUtil.isEmpty(areaChild)){
                areaChild = MapUtils.getString(param,"city");
                if(StringUtil.isNotEmpty(areaChild) && areaChild!=null){
                    hpd.setCity(areaChild);
                }else{
                    areaChild="深圳";
                    hpd.setCity(areaChild);
                }
            }
        }else {
            hpd.setCity(areaChild);
        }

        if (StringUtils.isEmpty(sid)) {
            sid = MapUtils.getString(param, "sid");
        }
        if (StringUtils.isEmpty(deviceId)) {
            deviceId = MapUtils.getString(param, "deviceId");
        }
        String uid = LoginCacheUtil.getUid(sid, deviceId);
        hpd.setUid(uid);


        return hpd;
    }

    /**
     * 更新房产信息接口过户税费，学位
     *
     * @return RespData
     */
    @ResponseBody
    @RequestMapping(value = "/v/updateBase")
    public RespDataObject<Map<String, Object>> updateHouseBase(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
        HouseHttpParamsDto hpd = getHttpHouseParams(request, param);
        param.put("uid", hpd.getUid());
        param.put("areaChild",null);
        if (StringUtils.isEmpty(hpd.getUid())) {
            RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
        } else {
            try {
                int i = houseService.updateHouse(param);
                Map<String, Object> map = houseService.selectHouseUpdateBase(param);
                RespHelper.setSuccessDataObject(resp, map);
            } catch (Exception e) {
                RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
                e.printStackTrace();
            }
        }

        return resp;
    }

    /**
     * 删除房产信息接口(批量或单个)
     *
     * @return RespData
     */
    @ResponseBody
    @RequestMapping(value = "/v/deleteBase")
    public RespDataObject<Map<String, Object>> deleteHouseBase(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        HouseHttpParamsDto hpd = getHttpHouseParams(request, param);
        RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
        String[] orderNoList = MapUtils.getString(param, "orderNoList").split(",");
        param.put("uid", hpd.getUid());
        param.put("areaChild", hpd.getCity());
        if (StringUtils.isEmpty(hpd.getUid())) {
            RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
        } else {
            //更新房产数据(伪删除)

            int temp = 0;
            try {
                for (int i = 0; i < orderNoList.length; i++) {
                    Map<String, Object> map = new HashedMap();
                    map.put("orderNo", orderNoList[i]);
                    map.put("state", 1);
                    temp = houseService.updateHouse(map);
                }

            } catch (Exception e) {

                e.printStackTrace();
            }
            //获取房产总价信息
            Map<String, Object> map = new HashedMap();
            try {
                List<Map<String, Object>> list=houseService.selectHouseList(param);
                int sumPrice=0;
                int appreciation=0;
                int loanBalance=0;
                for(int i=0;i<list.size();i++){
                    Map<String,Object> mapTemp=list.get(i);

                    sumPrice+=(int)(MapUtils.getDouble(mapTemp,"sumPrice")/10000);
                    appreciation+=(int)(MapUtils.getDouble(mapTemp,"appreciation")/10000);
                    loanBalance+=(int)(MapUtils.getDouble(mapTemp,"loanBalance")/10000);
                }

                map.put("sumPrice",sumPrice-loanBalance);
                map.put("appreciation",appreciation);
                map.put("houseList",list);
                if (MapUtils.isNotEmpty(map)) {
                    RespHelper.setSuccessDataObject(resp, map);
                } else {
                    resp.setData(null);
                    resp.setCode(RespStatusEnum.SUCCESS.getCode());
                    resp.setMsg("暂无数据请添加房产后查看");
                }

            } catch (Exception e) {

                RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
                e.printStackTrace();
            }
        }

        return resp;
    }

    /**
     * 查询房产详情
     *
     * @param request
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/v/hosueBaseDetail")
    public RespDataObject<Map<String, Object>> selectHosueBaseDetail(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
        HouseHttpParamsDto hpd = getHttpHouseParams(request, param);
        param.put("uid", hpd.getUid());
        param.put("areaChild", hpd.getCity());

        if (StringUtils.isEmpty(hpd.getUid())) {
            RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
        } else {
            try {
                /**查询房产基本信息*/
                DecimalFormat df = new DecimalFormat("#,##0.00");//格式化设置
                Map<String, Object> map = houseService.selectHouseDetail(param);
                
                String houseId = MapUtils.getString(map, "id");
                if(StringUtils.isNotEmpty(houseId))
                	new StatisticsController().statisticsHouseDetail(request, houseId);//统计数据浏览量

               /* map.put("sumPrice",df.format(MapUtils.getDouble(map,"sumPrice")));
                map.put("appreciation",df.format(MapUtils.getDouble(map,"appreciation")));*/

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String l = MapUtils.getString(map, "boughtTime");
                String dateStr ="";
                if(StringUtils.isNotEmpty(l)){
                    Date t = sdf.parse(l);
                    dateStr = sdf.format(t);
                }
                //房产更新时间
                map.put("updateTime",sdf.format(new Date()));
                map.put("boughtTime", dateStr);
                /**根据基本信息封装(小区成交、在售信息。小区成交量，房产总值月变化统计表)*/
                Double appreciationOf=houseService.complateAvgLastMouth(map);
                Map<String, Object> houseDetailCountMap = houseService.getHouseDetailCountMap(map);
                map.put("appreciationOf",appreciationOf);
                map.putAll(houseDetailCountMap);
                resp.setData(map);
                resp.setCode(RespStatusEnum.SUCCESS.getCode());
                resp.setMsg(RespStatusEnum.SUCCESS.getMsg());
                //RespHelper.setSuccessDataObject(resp, map);
                //resp.setData(map);
            } catch (Exception e) {
                RespHelper.setFailDataObject(resp,null, RespStatusEnum.ERRORONE.getMsg());
                e.printStackTrace();
            }
        }

        return resp;
    }

    /**
     * 获取房产信息管理页面数据
     *
     * @param request
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/v/hosueAessetDetail")
    public RespDataObject<Map<String, Object>> getHouseAessetManagement(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
        HouseHttpParamsDto hpd = getHttpHouseParams(request, param);
        param.put("uid", hpd.getUid());
        param.put("areaChild", hpd.getCity());
        Map<String, Object> map = null;
        if (StringUtils.isEmpty(hpd.getUid())) {
            RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
        } else {
            try {
                map = houseService.assetManagement(param);
                if (MapUtils.isNotEmpty(map)) {
                    RespHelper.setSuccessDataObject(resp, map);
                } else {
                    resp.setData(null);
                    resp.setCode(RespStatusEnum.FAIL.getCode());
                    resp.setMsg("暂无数据");
                }
            } catch (Exception e) {
                RespHelper.setFailDataObject(resp, null, RespStatusEnum.FAIL.getMsg());
                e.printStackTrace();
            }
        }
        return resp;
    }

    /**
     * 小区动态成交（小区成交数据根据参数查看更多）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/v/marketBargainMore")
    public RespDataObject<List<Map<String,Object>>> selectMarketBargainMore(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        RespDataObject<List<Map<String,Object>>> resp=new RespDataObject<List<Map<String, Object>>>();
        try {
            List<Map<String,Object>> bargainMore=houseService.selectDynamicCellBarginMoreList(param);
            if(CollectionUtils.isNotEmpty(bargainMore)){
                RespHelper.setSuccessDataObject(resp, bargainMore);
            }else{
                resp.setData(null);
                resp.setMsg("操作成功，暂无数据");
                resp.setCode(RespStatusEnum.SUCCESS.getCode());
            }
        } catch (Exception e) {
            RespHelper.setFailDataObject(resp,null,RespStatusEnum.FAIL.getMsg());
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 小区动态在售（网络报盘根据参数查看更多）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/v/dynamicCellSaleMore")
    public RespDataObject<List<Map<String,Object>>> selectDynamicCellSaleMore(HttpServletRequest request, @RequestBody Map<String, Object> param) {
        RespDataObject<List<Map<String,Object>>> resp=new RespDataObject<List<Map<String, Object>>>();
        try {
            List<Map<String,Object>> saleMore=houseService.selectDynamicCellSaleMoreList(param);
            if(CollectionUtils.isNotEmpty(saleMore)){
                RespHelper.setSuccessDataObject(resp,saleMore);
            }else{
                resp.setData(null);
                resp.setMsg("操作成功，暂无数据");
                resp.setCode(RespStatusEnum.SUCCESS.getCode());
            }

        } catch (Exception e) {
            RespHelper.setFailDataObject(resp,null,RespStatusEnum.FAIL.getMsg());
            e.printStackTrace();
        }
        return resp;
    }

    @ResponseBody
    @RequestMapping(value = "/selectHouseDetailById")
    public RespDataObject<Map<String,Object>> selectHouseDetailById(HttpServletRequest request,@RequestBody Map<String,Object> param) {
        RespDataObject<Map<String,Object>> resp=new RespDataObject<Map<String, Object>>();
        try {
            String id=MapUtils.getString(param,"id");
            Map<String,Object> house=houseService.selectHouseDetailById(id);
            if(MapUtils.isNotEmpty(house)){
                RespHelper.setSuccessDataObject(resp,house);
            }else{
                resp.setData(null);
                resp.setMsg("暂无数据");
                resp.setCode(RespStatusEnum.FAIL.getCode());
            }

        } catch (Exception e) {
            RespHelper.setFailDataObject(resp,null,RespStatusEnum.FAIL.getMsg());
            e.printStackTrace();
        }
        return resp;
    }





}
